package com.hxc.common.service;

import java.io.IOException;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

@Service
public class MarkDownV3Service {
  public static void main(String[] args) {
    String accessToken = "a03155c1ef9f90ee3c7ddf4bbc86443c";
    String owner = "spring-in-huangxian-county";
    String repo = "search_markdown_data";
    String path = "data";

    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
      // 发起获取文件列表的请求
      HttpGet listFilesRequest = new HttpGet("https://gitee.com/api/v5/repos/" + owner + "/" + repo + "/contents/" + path + "?access_token=" + accessToken);
      CloseableHttpResponse listFilesResponse = httpClient.execute(listFilesRequest);

      // 处理文件列表的响应
      if (listFilesResponse.getStatusLine().getStatusCode() == 200) {
        String responseBody = EntityUtils.toString(listFilesResponse.getEntity());
        System.out.println("Markdown files in the specified path: " + responseBody);
        JSONArray files = new JSONArray(responseBody);
        for (int i = 0; i < files.length(); i++) {
          JSONObject file = files.getJSONObject(i);
          if ("file".equals(file.getString("type")) && file.getString("name").endsWith(".md")) {
            HttpGet fileContentRequest = new HttpGet(file.getString("download_url") + "?access_token=" + accessToken);
            CloseableHttpResponse fileContentResponse = httpClient.execute(fileContentRequest);
            if (fileContentResponse.getStatusLine().getStatusCode() == 200) {
              String fileContent = EntityUtils.toString(fileContentResponse.getEntity());
              System.out.println("Content of " + file.getString("name") + ": " + fileContent);
            }
          }
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
